package com.dlc.felear.xiaoensale.activity;

import android.content.Intent;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;

import com.dlc.felear.xiaoensale.R;
import com.dlc.felear.xiaoensale.adapter.SideDishAdapter;
import com.dlc.felear.xiaoensale.constant.Constant;
import com.dlc.felear.xiaoensale.constant.TempData;
import com.dlc.felear.xiaoensale.customView.ConfirmDialog;
import com.dlc.felear.xiaoensale.customView.LoadingDialog;
import com.dlc.felear.xiaoensale.customView.SelectGridviewDialog;
import com.dlc.felear.xiaoensale.customView.SelectListDialog;
import com.dlc.felear.xiaoensale.customView.ShowTispMsgDialog;
import com.dlc.felear.xiaoensale.dao.CookingMenuDao;
import com.dlc.felear.xiaoensale.dao.MenuFoodMaterialDao;
import com.dlc.felear.xiaoensale.deviceUtil.TopbarHelper;
import com.dlc.felear.xiaoensale.entity.CookingMenu;
import com.dlc.felear.xiaoensale.entity.DeviceInfo;
import com.dlc.felear.xiaoensale.entity.MenuFoodMaterial;
import com.dlc.felear.xiaoensale.entity.Msg;
import com.dlc.felear.xiaoensale.entity.SideDish;
import com.dlc.felear.xiaoensale.entity.WeightInfo;
import com.dlc.felear.xiaoensale.helper.JsonHelper;
import com.dlc.felear.xiaoensale.helper.LoadDataHelper;
import com.dlc.felear.xiaoensale.helper.SendData;
import com.dlc.felear.xiaoensale.utils.NetUtil;
import com.dlc.felear.xiaoensale.utils.NumToStringUtil;
import com.itdlc.android.library.base.BaseActivity;
import com.itdlc.android.library.utils.APPDidUtil;

import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subscriber;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 配菜台--净重
 */
public class SuttleWeightActivity extends BaseActivity implements ConfirmDialog.ConfirmDialogCallback,
        SelectListDialog.DoubleDialogCallback ,SelectGridviewDialog.SelectDialogCallback {
    public static final String TAG = "SuttleWeightActivity";
    public static final String EVENT_BUS_TAG = "EVENT_BUS_TAG_SW";
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.rw_mac)
    TextView tvVersion;
    @BindView(R.id.tv_gg)
    TextView tvGg;
    @BindView(R.id.lv)
    ListView lv;
    private TopbarHelper topbarHelper;
    private SideDishAdapter adapter;
    private Map<Integer, Integer> oriWeights;
    private Map<Integer, Integer> tempWeights;
    private boolean isHide = false;
    private CookingMenuDao cookingMenuDao;
    private int tempGg = 0;
    private float tempGg1 = 0;
    private LoadingDialog loadingDialog;
    private boolean isDelete;
    private ConfirmDialog confirmDialog;
    private String cookMenuId;
    private int flag = 0;
    private long temptimestamp = 0;
    private SelectListDialog selectListDialog;
    private ShowTispMsgDialog showMsgDialog;
    private CookingMenu cookingMenu;
    private String deviceId = "";
    private List<DeviceInfo> tempList;
    private DeviceInfo tempDeviceInfo;
    private ShowTispMsgDialog dialog;
    private String sclaNos = "";
    private MenuFoodMaterialDao foodMaterialDao;
    private SelectGridviewDialog selectGridviewDialog;
    private List<String> menuData;



    @Override
    protected int getLayoutRes() {
        EventBus.getDefault().register(this);
        return R.layout.activity_suttle_weight;
    }


    @Override
    protected void initData() {
        menuData= TempData.getMenuType();
        EventBus.getDefault().post(4, Constant.POND_SIZE);
        NetUtil.getNetWrokState(this);
        selectGridviewDialog=new SelectGridviewDialog(this,this);
        topbarHelper = new TopbarHelper(this);
        topbarHelper.setTitle("菜谱配菜工具");
        topbarHelper.setcon(R.drawable.small_clock_icon);
        topbarHelper.setNavActivity(FirstActivity.class);
        topbarHelper.setReturnEnable(true);
        selectListDialog = new SelectListDialog(this, this);
        String appId = APPDidUtil.getAppDid();
        int length = appId.length();
        tvVersion.setText("编号:" + appId.substring(length - 4));
        adapter = new SideDishAdapter(this);
        lv.setAdapter(adapter);
        oriWeights = new HashMap<>();
        tempWeights = new HashMap<>();
        cookingMenuDao = new CookingMenuDao(this);
        confirmDialog = new ConfirmDialog(this, this);
        showMsgDialog = new ShowTispMsgDialog(this);
        foodMaterialDao = new MenuFoodMaterialDao(this);
    }

    @OnClick({R.id.btn_clear, R.id.btn_cp, R.id.r_iv_jianj, R.id.btn_fs,
            R.id.r_iv_jiaj, R.id.btn_commit})
    public void clickView(View view) {
        switch (view.getId()) {
            case R.id.btn_clear:
                initWeight();
                break;
            case R.id.btn_cp:
                deleteEmnu();
                selectGridviewDialog.showDialog(menuData);
                break;
            case R.id.r_iv_jianj:
                editValue(-0.5f);
                break;
            case R.id.btn_fs:
                showSelectDialog();
                break;
            case R.id.r_iv_jiaj:
                editValue(0.5f);
                break;
            case R.id.btn_commit:
                if (NetUtil.isNetConnected()) {
                    confirmDialog.showDialog("确定上传数据吗");
                } else {
                    showShortToast("网络异常，请连接网络");
                }
                break;
        }
    }

    /**
     * 显示发送菜谱信息弹窗
     */
    private void showSelectDialog() {
        try {
            if (tempList == null || tempList.isEmpty()) {
                SendData.getDevices(20);
                return;
            }
            String weight = getCurrentMenuWeight();
            selectListDialog.setTips("炒菜机", "菜品重量");
            if (cookingMenu == null) {
                showShortToast("请先选择菜谱");
                return;
            }
            if (Float.parseFloat(weight) < 1f) {
                showShortToast("请先配菜，再点击发送菜谱");
                return;
            }
            if (tempDeviceInfo != null) {
                selectListDialog.setHintMsg(tempDeviceInfo.getName(), weight);
            } else {
                selectListDialog.setHintMsg("请选择目标炒菜机", weight);
            }
            selectListDialog.showDialog(tempList);
        } catch (Exception e) {
            showShortToast("数据异常");
        }
    }

    /**
     * 发送前菜谱信息检验
     *
     * @param weight
     * @param deviceId
     */
    private void checkMenuInfo(float weight, String deviceId) {
        try {
            if (tempDeviceInfo == null || TextUtils.isEmpty(deviceId)) {
                showShortToast("请先选择炒菜机");
                return;
            }
            Log.e(TAG, "Model:" + tempDeviceInfo.getModel() + " cookingMenu:" + JsonHelper.toJson(cookingMenu));
            if (!TextUtils.equals(tempDeviceInfo.getModel(), getMachineModoel(cookingMenu.getMachineModoel()))) {
                showShortToast("选择的菜谱和机器型号不一致，请重新选择");
                return;
            }
            if (weight < getMiniWeight(cookingMenu.getMachineModoel())) {
                showShortToast("炒菜机最小重量为" + getMiniWeight(cookingMenu.getMachineModoel()) + "斤");
                return;
            }
            if (cookingMenu == null) {
                showShortToast("请先选择菜谱");
                return;
            }
            sendInfo(cookingMenu.getId(), cookingMenu.getName(),
                    NumToStringUtil.spitDouble(weight, 1), deviceId);
        } catch (Exception e) {
            showShortToast("数据异常:" + e.getMessage());
        }
    }

    private String getMachineModoel(String m) {
        if (TextUtils.isEmpty(m)) {
            return "M400";
        }

        return m;
    }

    private int getMiniWeight(String machineModoel) {
        int temp = 4;
        if (TextUtils.equals(machineModoel, "M240")) {
            temp = 1;
        }
        if (TextUtils.equals(machineModoel, "M500")) {
            temp = 5;
        }
        return temp;
    }


    private String getCurrentMenuWeight() {
        int weight = 0;
        for (SideDish sideDish : adapter.getData()) {
            weight += sideDish.getWeight();
        }
        double temp = weight / 500f;
        return NumToStringUtil.spitDouble(temp, 1);
    }

    private void sendInfo(String id, String name, String size, String deviceId) {
        Map<String, Object> p = new HashMap<>();
        p.put("deviceId", APPDidUtil.getAppDid());
        p.put("id", id);
        p.put("name", name);
        p.put("size", size);
        Map<String, Object> info = new HashMap<>();
        info.put("option", 1);
        info.put("data", p);
        Log.e(TAG, "发送信息:" + JsonHelper.toJson(p));
        SendData.sendSocketInfo(info, deviceId, showMsgDialog);
    }


    private void deleteEmnu() {
        if (!isDelete) {
            isDelete = true;
            LoadDataHelper.getInstance(this).deleteEMNU();
        }
    }

    private void editValue(float value) {
        if (adapter.getData().isEmpty()) {
            showShortToast("请先选择菜谱");
            return;
        }
        tempGg1 = tempGg1 + value;
        if (tempGg1 < 0) {
            tempGg1 = 0;
        }
        Log.e(TAG, "tempGg1=" + tempGg1);
        setTvSpecification(NumToStringUtil.spitDouble(tempGg1, 1));
        adapter.editStdWeight(tempGg1);
    }

    @Override
    protected void onResume() {
        super.onResume();
        isHide = false;
        SendData.getDevices(20);
    }

    @Override
    protected void onStop() {
        super.onStop();
        isHide = true;
    }

    @Subscriber(tag = Constant.EVENTBUS_TAG_ACTION_TAKE_PUT)
    public void recieveWeight(WeightInfo weightInfo) {
        tempWeights.put(weightInfo.getNum(), weightInfo.getWeight());
        if (isHide || !ignore(weightInfo)) {
//            Log.e(TAG, "忽略：" + weightInfo.getNum());
            return;
        }
        int temp = getOriWeight(weightInfo.getNum()) - weightInfo.getWeight();
        if (temp > 100) {
//            Log.e(TAG, "num=" + weightInfo.getNum() + " weight:" + temp);
        }
        temp = temp > 0 ? temp : 0;
        weightInfo.setWeight(temp);
        adapter.setWeightInfo(weightInfo);
    }

    private boolean ignore(WeightInfo weightInfo) {
        return sclaNos.contains(Integer.toString(weightInfo.getNum()));
    }

    private int getOriWeight(int num) {
        if (oriWeights.containsKey(num)) {
            return oriWeights.get(num);
        }

        return -1;
    }


    @Subscriber(tag = Constant.EVENTBUS_TAG_RFID_INFO)
    public void recieveRfid(String cardNum) {
        if (isHide) {
            return;
        }
        Log.e(TAG, "cardNum=" + cardNum);
        if (TextUtils.equals(cardNum, Constant.LEFT_CARD)) {
            //ic 卡离开
            adapter.setEnbale(false);
            adapter.initData();
            cearData();
        } else {
            //放卡
            adapter.setEnbale(true);
            initWeight();
            getCookMenu(cardNum);
        }
    }


    private void cearData() {
        tvGg.setText("");
        tvName.setText("");
    }

    private void getCookMenu(String no) {
        try {
            List<CookingMenu> list = cookingMenuDao.queryForMacNo(no);
            if (list == null || list.isEmpty()) {
                showShortToast("此卡没有绑定菜谱，请绑定再使用");
                return;
            }
            showMenuInfo(list.get(0));
        } catch (Exception e) {
            Log.e(TAG, e.getMessage());
        }
    }

    private void showMenuInfo(CookingMenu cookingMenu) {
        try {
            if (cookingMenu == null) {
                showShortToast("数据为空");
                return;
            }
            initWeight();
            cookMenuId = cookingMenu.getId();
            cacheScaleNo(cookingMenu);
            Log.e(TAG, "菜谱:" + JsonHelper.toJson(cookingMenu));
            tvName.setText(cookingMenu.getName());
            setTvSpecification(cookingMenu.getSpecification());
            adapter.setCookMenu(cookingMenu);
            tempGg = Integer.parseInt(cookingMenu.getSpecification());
            tempGg1 = tempGg;
        } catch (Exception e) {
            Log.e(TAG, e.getMessage());
        }
    }

    private void cacheScaleNo(CookingMenu cookingMenu) {
        List<MenuFoodMaterial> list = foodMaterialDao.queryForAllByCId(cookingMenu.getId());
        if (list == null) {
            sclaNos = "1234";
            return;
        }
        sclaNos = "";
        for (MenuFoodMaterial material : list) {
            sclaNos += Integer.toString(material.getNumber());
        }
        Log.e(TAG, "sclaNos:" + sclaNos);
    }

    private void setTvSpecification(String value) {
        try {
            tvGg.setText(value + "斤");
        } catch (Exception e) {

        }
    }

    @Subscriber(tag = Constant.EVENTBUS_TAG_HTTP_RESULT)
    public void recieveHttpResult(Msg msg) {
        closeLoadingDialog();
        if (!TextUtils.isEmpty(msg.getMsg())) {
            showShortToast(msg.getMsg());
        } else if (!TextUtils.isEmpty(msg.getMessage())) {
            showShortToast(msg.getMessage());
        }
    }

    private int getMapValue(int key, Map<Integer, Integer> map) {
        if (map == null || !map.containsKey(key)) {
            return 0;
        }

        return map.get(key);
    }

    private void initWeight() {
        reSetWeight();
        jumpSetting();
        if (adapter.getData().isEmpty()) {
            showShortToast("请选择菜谱");
            return;
        }
        showShortToast("请开始配菜");
        for (Integer num : tempWeights.keySet()) {
            oriWeights.put(num, tempWeights.get(num));
        }
    }

    private void reSetWeight() {
        for (Integer num : tempWeights.keySet()) {
            oriWeights.put(num, tempWeights.get(num));
        }
    }


    private void jumpSetting() {
        if (System.currentTimeMillis() - temptimestamp > 2500) {
            flag = 0;
            temptimestamp = System.currentTimeMillis();
        }
        if (flag > 10) {
            startActivity(new Intent(Settings.ACTION_SETTINGS));
            flag = 0;
        }
        flag++;
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        try {
            if (requestCode == 1024) {
                initWeight();
                String id = data.getExtras().getString("id");
                getCookMenuById(id);
            }
        } catch (Exception e) {
            showShortToast("数据异常");
        }
    }

    private void getCookMenuById(String id) {
        try {
            cookingMenu = cookingMenuDao.queryById(id);
            showMenuInfo(cookingMenu);
        } catch (Exception e) {
            Log.e(TAG, e.getMessage());
        }
    }

    private void uplaodMerial(List<SideDish> data) {
        if (data == null || data.isEmpty()) {
            showShortToast("食材不能为空");
            return;
        }
        showLoadDialog();
        SendData.uplaodSuttleFoodMaterial(cookMenuId, data, 2);
    }

    private void showLoadDialog() {
        if (loadingDialog == null) {
            loadingDialog = new LoadingDialog(this, "数据上传中...");
        }
        loadingDialog.show();
    }

    private void closeLoadingDialog() {
        if (loadingDialog != null) {
            loadingDialog.close();
        }
    }


    @Override
    public void selectResult(int value, int id) {
        if (value == 1) {
            uplaodMerial(adapter.getData());
        }
    }

    @Subscriber(tag = EVENT_BUS_TAG)
    private void recieveDeviceInfo(List<DeviceInfo> list) {
        try {
            tempList = list;
            Log.e(TAG, "炒菜机数据:" + JsonHelper.toJson(tempList));
        } catch (Exception e) {
            Log.e(TAG, e.getMessage());
        }
    }

    @Override
    public void doubleDialogInputResult(float weight, DeviceInfo deviceInfo) {
        Log.e(TAG, "选择发送的信息:weight=" + weight + " 设备信息:" + JsonHelper.toJson(deviceInfo));
        if (deviceInfo != null) {
            tempDeviceInfo = deviceInfo;
            checkMenuInfo(weight, deviceInfo.getDeviceId());
        }
    }


    @Subscriber(tag = Constant.DEVICE_ERROR_MSG_SHOW)
    public void warnErrorMsg(String msg) {
//        Log.e(TAG,"error msg:"+msg);
        if (dialog == null) {
            dialog = new ShowTispMsgDialog(this);
        }
        if (TextUtils.isEmpty(msg)) {
            dialog.closeDialog();
            return;
        }
        dialog.setMsg(msg);
        dialog.setDialog("设备故障");
    }

    @Subscriber(tag = Constant.SHOW_MSG_FOR_DIALOG)
    public void showMsfForDialog(String msg) {
        if (showMsgDialog != null) {
            showMsgDialog.setDialog(msg, 1000);
        }
    }

    @Override
    public void onItemClickResult(String result) {
        Intent intent=new Intent(this,
                MenuList1Activity.class);
        intent.putExtra("type",result);
        startActivityForResult(intent, 1024);
    }
}
